import React, { useState, useEffect } from 'react';
import { TjContent, TjModal, TjModalTitle } from '@/tjComponents';
import { Button, Form, message, Modal } from 'antd';
import { ExclamationCircleOutlined, PlusCircleOutlined } from '@ant-design/icons';
import _ from 'lodash';
import TjTable from '@/pages/ETrade/components/TjTable';
import moment from 'moment';
import { columns } from './helper';
import {
  deleteStationBaseConfigData,
  queryStationBaseConfigData,
  updateStationBaseConfigData,
} from '../../service';
import { HttpCode } from '#/utils/contacts.js';
import type { TreeDatatype } from '@/hooks/useRequestPowerAfterInit';
import './index.less';
import { useForm } from 'antd/lib/form/Form';
import { EditTabelRowStyle } from '../../helper';
import MxModalContent from '../MxModalContent';

const { confirm } = Modal;

const MxConfig: React.FC<IMxConfigProps> = (props) => {
  const [loading, setLoading] = useState<boolean>(false);
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [form] = useForm();

  const changeLoading = (status: boolean) => {
    props.changeGlobalLoading && props.changeGlobalLoading(status);
    setLoading(status);
  };

  const query = () => {
    changeLoading(true);
    const years = _.get(props.filterValues, 'year', []);
    const stationIdList = _.get(props.filterValues, 'stationIdList', []);
    const obj = {
      startYear: moment(years[0]).format('YYYY'),
      endYear: moment(years[1]).format('YYYY'),
      stationIdList,
      marketId: props.marketId,
      menuCode: props.menuCode,
    };
    queryStationBaseConfigData(obj)
      .then((res) => {
        if (res.statusCode === HttpCode.SUCCESS) {
          const stations = _.get(props.currentProvinceInfo, 'stations', []);
          if (res.data && res.data.length > 0 && stations.length > 0) {
            const formValues: any = {};
            res.data.forEach((v: any) => {
              v.stationName = stations.find(
                (s: any) => v.stationIdList[0] === s.stationId,
              ).stationName;
              formValues[`list@${v.id}`] = [];
              if (v.list) {
                v.list.forEach((item: any) => {
                  if (item.baseFlag) {
                    formValues[`list@${v.id}`].push(item.month);
                  }
                });
              }
            });
            form.setFieldsValue(formValues);
            setDataSource(res.data);
          } else {
            setDataSource([]);
          }
        }
      })
      .finally(() => {
        changeLoading(false);
      });
  };

  const add = () => {
    const stations = _.get(props.currentProvinceInfo, 'stations', []);
    const initValue: any = {
      year: moment(),
    };
    initValue.stationIdList = stations.map((v: any) => v.stationId);
    TjModal.open({
      title: <TjModalTitle title="新增" />,
      width: 1000,
      destroyOnClose: true,
      maskClosable: false,
      content: (
        <MxModalContent
          treeData={props.treeData}
          marketId={props.marketId}
          initValue={initValue}
          type="add"
          currentProvinceInfo={props.currentProvinceInfo}
        />
      ),
      onOk: (values) => {
        const params: any = {
          marketId: props.marketId,
          year: moment(values.year).format('YYYY'),
          stationIdList: values.stationIdList,
          list: values.list,
          strategyType: props.strategyType,
        };
        return new Promise((resolve, reject) => {
          updateStationBaseConfigData(params)
            .then((res) => {
              if (res.statusCode === HttpCode.SUCCESS) {
                resolve('');
                message.success('新建成功');
                query();
              } else {
                reject();
                message.error(res.message);
              }
            })
            .finally(() => {
              changeLoading(false);
            });
        });
      },
    });
  };

  const view = (id: number, index: number) => {
    const row = dataSource[index];
    const initValue = {
      year: moment(`${row.year}`),
      stationIdList: row.stationIdList,
      list: row.list,
    };
    TjModal.open({
      title: <TjModalTitle title="查看" />,
      width: 1000,
      footer: null,
      content: (
        <MxModalContent
          treeData={props.treeData}
          marketId={props.marketId}
          initValue={initValue}
          type="view"
          currentProvinceInfo={props.currentProvinceInfo}
        />
      ),
    });
  };

  const rowAdd = (id: number, index: number) => {
    const row = dataSource[index];
    const initValue = {
      year: moment(`${row.year}`),
      stationIdList: row.stationIdList,
      list: row.list.map((v: any) => {
        return {
          ...v,
          editor: true,
        };
      }),
    };
    TjModal.open({
      title: <TjModalTitle title="新增" />,
      width: 1000,
      content: (
        <MxModalContent
          treeData={props.treeData}
          marketId={props.marketId}
          initValue={initValue}
          type="addRow"
          currentProvinceInfo={props.currentProvinceInfo}
        />
      ),
      onOk: (values) => {
        const params: any = {
          marketId: props.marketId,
          year: moment(values.year).format('YYYY'),
          stationIdList: values.stationIdList,
          list: values.list,
          strategyType: props.strategyType,
        };
        return new Promise((resolve, reject) => {
          updateStationBaseConfigData(params)
            .then((res) => {
              if (res.statusCode === HttpCode.SUCCESS) {
                resolve('');
                message.success('新建成功');
                query();
              } else {
                reject();
                message.error(res.message);
              }
            })
            .finally(() => {
              changeLoading(false);
            });
        });
      },
    });
  };

  const del = (id: number, index: number) => {
    confirm({
      title: '是否确认删除',
      icon: <ExclamationCircleOutlined />,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        deleteStationBaseConfigData({
          idList: [id],
        }).then((res) => {
          if (res.statusCode === HttpCode.SUCCESS) {
            message.success('删除成功');
            query();
          } else {
            message.error(res.message);
          }
        });
      },
    });
  };

  useEffect(() => {
    query();
  }, [props.filterValues]);

  return (
    <TjContent
      className="mx-config"
      titleLeft="蒙西现货"
      titleRight={
        <Button type="link" icon={<PlusCircleOutlined />} loading={loading} onClick={add}>
          新建
        </Button>
      }
    >
      <Form form={form}>
        <TjTable
          isLoading={loading}
          components={{ Cell: EditTabelRowStyle }}
          columns={columns(rowAdd, view, del)}
          dataSource={dataSource}
          primaryKey="id"
        />
      </Form>
    </TjContent>
  );
};

interface IMxConfigProps {
  marketId: string;
  marketName?: string;
  currentProvinceInfo?: any;
  menuCode?: string;
  treeData: TreeDatatype[];
  strategyType?: string;
  filterValues?: any;
  changeGlobalLoading?: (loading: boolean) => void;
}

export default MxConfig;
